package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.CookieStore;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oracle.jrockit.jfr.RequestableEvent;

import dao.FindPasswordDao;
import dao.UserDAO;
import entity.User;

/**
 * Servlet implementation class UserLogin
 */
@WebServlet("/FindPassword")
public class FindPassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDAO userDAO = UserDAO.getInstance();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindPassword() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		HttpSession session = (HttpSession)request.getSession(true);
		String user_id = (String)request.getParameter("userid");
		String verification_code = request.getParameter("verification_code");
		String user_password = request.getParameter("new_password");
		
		FindPasswordDao ps = FindPasswordDao.getInstance();

		
		String result = "";
		String nextInfo = "";
		String nextURL = "";
		int id=Integer.parseInt(user_id);
		if(user_id!="" && verification_code!="" && user_password!="") {
			
			if(!verification_code.equals(ps.getCode(id))) {
				result = "验证码错误！";
				nextInfo = "返回上一页";
				nextURL = "FindPassword.jsp";
			}else {
				if(ps.updatePassword(id, user_password)) {
					result="密码重置成功！";
					nextInfo = "返回主页";
					nextURL = "Index_Date";
				}else {
					result="密码重置失败！";
					nextInfo = "返回上一页";
					nextURL = "FindPassword.jsp";
				}
			}
		}
		
		session.setAttribute("find_password_result", result);
		session.setAttribute("find_password_nextInfo", nextInfo);
		session.setAttribute("find_password_nextURL", nextURL);

		response.sendRedirect("UpdatePasswordResult.jsp");
			
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
